package com.example.controller;


import com.example.model.Files;
import com.example.service.FilesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("/file")
//@MultipartConfig
public class FileController {

    private static final String FILE_PATH_PREFIX = "D:/ketangpai666/uploads/";
    private static final String FILE = "D:/ketangpai666/";
    @Autowired
    FilesService filesService;
    Files files = new Files();

    @PostMapping("/upload")
//    @MultipartConfig
    public String uploadFile(@RequestParam("file") MultipartFile file,
                             @RequestParam("studentName") String studentName, @RequestParam("fileId") int fileId) throws  IOException {
        return filesService.insertFile(files,file,studentName,fileId);

        //存入数据库

    }

    @GetMapping("/list")
    public List<Files> getAllFiles(@RequestParam("taskId") String taskId){

        return filesService.findFileAll(taskId);
    }

    @GetMapping("/download/{id}")
    public ResponseEntity<Resource> downloadfiles(@PathVariable String id) throws IOException {

            Path filePath = Paths.get(FILE_PATH_PREFIX, filesService.findFileId(id));
            Resource resource = new UrlResource(filePath.toUri());
        String encodedFileName = URLEncoder.encode(resource.getFilename(), StandardCharsets.UTF_8);
        System.out.println( resource.getFilename());
        System.out.println( encodedFileName);

            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"")
                    .body(resource);
        }
        @PostMapping("/status")
       public void status(@RequestParam("fileId")int fileId,@RequestParam("statusFile")String statusFile){
        filesService.status(fileId,statusFile);
        }
        @GetMapping("findStatus")
    public String[] findStatus(@RequestParam("taskId")String taskId){
        return filesService.status(taskId);
        }
    }



